package com.example.j20240422springtrans.controller;

import com.example.j20240422springtrans.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/trans")
public class TransController {
    @Autowired
    private UserService userService;
    @Transactional
    @RequestMapping("/registry")
    public Boolean registry(String userName, String password) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return false;
        }
        userService.registry(userName, password);

        //异常回滚
        //int a = 10 / 0;

        //手动回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return true;
    }


    @Transactional
    @RequestMapping("/test")
    public Boolean test(String userName, String password) throws RuntimeException {
        userService.registry(userName, password);
        if(true) {
            throw new RuntimeException();
        }
        return true;
    }

    @SneakyThrows
    @Transactional
    @RequestMapping("/test1")
    public Boolean test1(String userName, String password) throws IOException {
        userService.registry(userName, password);
        if(true) {
            throw new IOException();
        }
        return true;
    }

    @SneakyThrows
    @Transactional(rollbackFor = RuntimeException.class)
    @RequestMapping("/test2")
    public Boolean test2(String userName, String password) {
        userService.registry(userName, password);
        if(true) {
            throw new IOException();
        }
        return true;
    }

}
